<template>
  <div class="users-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchForm.nickNameFuzzy"
            placeholder="支持模糊搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData.list"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <Avatar :userId="row.userId" :avatar="row.qqAvatar" />
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="昵称" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="空间使用">
          <template #default="{ row }">
            {{ proxy.Utils.size2Str(row.useSpace) }} / {{ proxy.Utils.size2Str(row.totalSpace) }}
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="加入时间" />
        <el-table-column prop="lastLoginTime" label="最后登录时间" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleUpdateSpace(row)"
            >
              分配空间
            </el-button>
            <el-button
              link
              :type="row.status === 0 ? 'success' : 'danger'"
              @click="handleUpdateStatus(row)"
            >
              {{ row.status === 0 ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="tableData.pageNo"
          v-model:page-size="tableData.pageSize"
          :total="tableData.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 分配空间对话框 -->
    <el-dialog
      v-model="spaceDialog.visible"
      title="分配空间"
      width="500px"
      @close="resetSpaceForm"
    >
      <el-form
        ref="spaceFormRef"
        :model="spaceForm"
        :rules="spaceRules"
        label-width="100px"
      >
        <el-form-item label="用户昵称">
          <span>{{ spaceForm.nickName }}</span>
        </el-form-item>
        <el-form-item label="当前空间">
          <span>{{ proxy.Utils.size2Str(spaceForm.useSpace) }} / {{ proxy.Utils.size2Str(spaceForm.totalSpace) }}</span>
        </el-form-item>
        <el-form-item label="新空间大小" prop="changeSpace">
          <el-input-number
            v-model="spaceForm.changeSpace"
            :min="-1024 * 1024"
            :max="1024 * 1024"
            controls-position="right"
          >
            <template #suffix>MB</template>
          </el-input-number>
          <div class="space-tip">提示：输入负数可减少用户空间</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="spaceDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitSpaceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import Avatar from '@/components/Avatar.vue'

const { proxy } = getCurrentInstance()

const api = {
  loadUserList: '/admin/loadUserList',
  updateUserStatus: '/admin/updateUserStatus',
  updateUserSpace: '/admin/updateUserSpace'
}

// 搜索表单
const searchForm = ref({
  nickNameFuzzy: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref({
  pageNo: 1,
  pageSize: 10,
  totalCount: 0,
  list: []
})

// 空间分配对话框
const spaceDialog = ref({
  visible: false
})

const spaceForm = ref({})
const spaceFormRef = ref()
const spaceRules = {
  changeSpace: [
    { required: true, message: '请输入新空间大小' },
    { type: 'number', message: '空间大小必须为数字' }
  ]
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const result = await proxy.Request({
      url: api.loadUserList,
      params: {
        pageNo: tableData.value.pageNo,
        pageSize: tableData.value.pageSize,
        ...searchForm.value
      }
    })
    if (result) {
      tableData.value = result.data
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  tableData.value.pageNo = 1
  loadUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {}
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  tableData.value.pageSize = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  tableData.value.pageNo = val
  loadUserList()
}

// 更新用户状态
const handleUpdateStatus = (row) => {
  const newStatus = row.status === 0 ? 1 : 0
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  proxy.Confirm(`确定要${statusText}该用户吗？`, async () => {
    const result = await proxy.Request({
      url: api.updateUserStatus,
      params: {
        userId: row.userId,
        status: newStatus
      }
    })
    if (result) {
      proxy.Message.success(`${statusText}成功`)
      loadUserList()
    }
  })
}

// 分配空间
const handleUpdateSpace = (row) => {
  spaceDialog.value.visible = true
  spaceForm.value = {
    ...row,
    changeSpace: row.totalSpace / (1024 * 1024) // 转换为MB
  }
}

const submitSpaceForm = () => {
  spaceFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    const result = await proxy.Request({
      url: api.updateUserSpace,
      params: {
        userId: spaceForm.value.userId,
        changeSpace: spaceForm.value.changeSpace
      }
    })
    
    if (result) {
      proxy.Message.success('空间分配成功')
      spaceDialog.value.visible = false
      loadUserList()
    }
  })
}

const resetSpaceForm = () => {
  if (spaceFormRef.value) {
    spaceFormRef.value.resetFields()
  }
  spaceForm.value = {}
}

// 初始加载
loadUserList()
</script>

<style lang="scss" scoped>
.users-container {
  .search-card {
    margin-bottom: 20px;
    border: none;
    background: linear-gradient(to right, #fff, #fafafa);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
  }
  
  .table-card {
    border: none;
    background: linear-gradient(to right, #fff, #fafafa);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      
      span {
        font-size: 16px;
        font-weight: bold;
        background: linear-gradient(120deg, #bd34fe 30%, #47caff);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    
    :deep(.el-table) {
      background: transparent;
      
      th {
        background-color: #fafafa;
        font-weight: bold;
        color: #606266;
        
        &.is-leaf {
          border-bottom: 2px solid #EBEEF5;
        }
      }
      
      td {
        padding: 12px 0;
      }
      
      .el-button {
        padding: 6px 0;
        font-weight: normal;
        
        &.el-button--primary {
          color: #409EFF;
          
          &:hover {
            color: #66b1ff;
          }
        }
        
        &.el-button--danger {
          color: #F56C6C;
          
          &:hover {
            color: #f78989;
          }
        }
        
        &.el-button--success {
          color: #67C23A;
          
          &:hover {
            color: #85ce61;
          }
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      padding: 10px 20px;
      display: flex;
      justify-content: flex-end;
      background-color: #fafafa;
      border-top: 1px solid #f0f0f0;
    }
  }
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: bold;
      background: linear-gradient(120deg, #bd34fe 30%, #47caff);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
  
  .el-dialog__body {
    padding: 30px 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #f0f0f0;
    background-color: #fafafa;
  }
  
  .el-form-item {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }
  }
  
  .el-input-number {
    width: 100%;
  }
}

// 标签样式
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  
  &.el-tag--success {
    background-color: rgba(103, 194, 58, 0.1);
    border-color: rgba(103, 194, 58, 0.2);
    color: #67c23a;
  }
  
  &.el-tag--danger {
    background-color: rgba(245, 108, 108, 0.1);
    border-color: rgba(245, 108, 108, 0.2);
    color: #f56c6c;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .users-container {
    .search-card {
      .el-form-item {
        margin-right: 0;
        margin-bottom: 16px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .table-card {
      :deep(.el-table) {
        .el-button + .el-button {
          margin-left: 8px;
        }
      }
    }
  }
}
</style> 